#import "YcPluginLearnPlugin.h"
#import <SDWebImage/SDWebImage.h>
#import "YcPlatformViewFactory.h"

/**
 * 本插件项目主要演示以下几个方面，主要用于教学使用
 * 1。flutter与原生互相传递事件信息
 * 2。在原生项目中使用第三方包SDWebImage加载图片，主要用于演示如何在插件中使用第三方包
 * 2。flutter页面上嵌入原生view，并实现独立的事件互传
 */


@interface YcPluginLearnPlugin()<FlutterStreamHandler>

@property (nonatomic,strong) FlutterEventSink sink;


@end

@implementation YcPluginLearnPlugin


///入口方法
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    
    //初始化FlutterMethodChannel，与flutter MethodChannel('yc_plugin_learn')传入相同的字符串，大家在一个通道上
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"yc_plugin_learn"
                                     binaryMessenger:[registrar messenger]];
    
    //处理flutter与原生事件的一个对象,可以使用单例
    YcPluginLearnPlugin* instance = [[YcPluginLearnPlugin alloc] init];
    //进行绑定
    [registrar addMethodCallDelegate:instance channel:channel];
    
    //初始化事件通道，主要是获取这个FlutterEventSink sink，用这个sink发消息给flutter
    FlutterEventChannel * event = [FlutterEventChannel eventChannelWithName:@"yc_plugin_learn_eventChannel" binaryMessenger:registrar.messenger];
    [event setStreamHandler:instance];
    
    //这儿演示flutter加载原生view
    //注册PlatformViewFactory，用于展示原生view。在flutter中UiKitView显示viewType: "YcPluginLearnPlugin.testView",在这个位置
    [registrar registerViewFactory:[[YcPlatformViewFactory alloc] initWithMessenger:registrar] withId:@"YcPluginLearnPlugin.testView"];
    
}

//flutter触发事件
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    } else if ([@"getImage" isEqualToString:call.method]){
        [self getImageHandler:call result:result];
    } else if ([@"init" isEqualToString:call.method]){
        
        //接收到的数据
        NSDictionary *argumentsMap = call.arguments;
        NSLog(@"原生：%@",argumentsMap[@"appId"]);
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"code"] = @"1";
        dic[@"msg"] = @"success";
        result(dic);
    } else if ([@"test" isEqualToString:call.method]){
        //测试，给flutter不停地发消息
        for (int i=0; i<20000; i++) {
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"type"] = @"0";
            dic[@"second"] = [NSString stringWithFormat:@"%d",i];
            self.sink(dic);
        }
    }
    
    else {
        result(FlutterMethodNotImplemented);
    }
}


/**
 加载图片
 pod依赖在yc_plugin_learn目录下Pod-> yc_plugin_learn.podspec添加
 */
- (void)getImageHandler:(FlutterMethodCall*)call result:(FlutterResult)result{
    if(call.arguments != nil && call.arguments[@"url"] != nil){
        NSString *url = call.arguments[@"url"];
        
        if([url hasPrefix:@"localImage://"]){
            //获取本地图片
            NSString *imageName = [url stringByReplacingOccurrencesOfString:@"localImage://" withString:@""];
            UIImage *image = [UIImage imageNamed:imageName];
            if(image != nil){
                NSData *imgData = UIImageJPEGRepresentation(image,1.0);
                result(imgData);
            }else{
                result(nil);
            }
        }else {
            //获取网络图片
            UIImage *image = [[SDImageCache sharedImageCache] imageFromCacheForKey:url];
            if(!image){
                //本地无缓存，下载后返回图片
                [[SDWebImageDownloader sharedDownloader]
                 downloadImageWithURL:[[NSURL alloc] initWithString:url]
                 completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                    if(finished){
                        result(data);
                        [[SDImageCache sharedImageCache] storeImage:image forKey:url completion:nil];
                    }
                }];
            }else{
                //本地有缓存，直接返回图片
                NSData *imgData = UIImageJPEGRepresentation(image,1.0);
                result(imgData);
            }
        }
    }
}

//[event setStreamHandler:instance]; FlutterStreamHandler代理方法，用于获取FlutterEventSink sink
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    
    self.sink = events;
    return nil;
}
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    return nil;
}

@end

